package com.seamtop.cuber.web.controller.cuber;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seamtop.cuber.common.base.DataObject;
import com.seamtop.cuber.common.entriy.CuberReducer;
import com.seamtop.cuber.common.key.MatchUtil;
import com.seamtop.cuber.common.metadata.TableMetaData;
import com.seamtop.cuber.common.util.StringUtil;
import com.seamtop.cuber.web.service.ReducerService;
import com.seamtop.cuber.web.service.TableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.util.*;

/**
 * Created by zongjunfeng on 2015/10/13.
 */
@Controller("ReducerController")
public class ReducerController {

    @Autowired
    private ReducerService reducerService;

    @Autowired
    private TableService tableService;

    @RequestMapping("/cuber/addReducerIndex.shtml")
    public String addReducerIndex(HttpServletRequest request, HttpServletResponse response,
                                  ModelMap model) {
        List<TableMetaData> tableList = tableService.findTableList();
        model.addAttribute("tableList",tableList);
        return "/cuber/add_reducer_index";
    }



    @RequestMapping("/cuber/isReducerNameExist.shtml")
    public @ResponseBody
    JSONObject isReducerNameExist(HttpServletRequest request, HttpServletResponse response,
                                  ModelMap model) {
        JSONObject jsonObject = new JSONObject();
        String reducerName = request.getParameter("reducerName");
        HashMap<String,CuberReducer> reducerMap = DataObject.getCuberReducerMap();
        if(reducerMap.containsKey(reducerName)){
            jsonObject.put("result","fail");
        }else{
            jsonObject.put("result","success");
        }
        return jsonObject;
    }

    @RequestMapping("/cuber/changeReducerStatus.shtml")
    public @ResponseBody
    JSONObject changeReducerStatus(HttpServletRequest request, HttpServletResponse response,
                            ModelMap model) {
        String reducerName = request.getParameter("reducerName");
        String status = request.getParameter("status");
        JSONObject jsonObject = new JSONObject();
        if(StringUtil.isEmpty(status) || (!"0".equals(status) &&!"1".equals(status) && !"2".equals(status))){
            jsonObject.put("result","1");
            return jsonObject;
        }

        CuberReducer cuberReducer = DataObject.getCuberReducerMap().get(reducerName);
        if(cuberReducer == null){
            jsonObject.put("result","1");
            return jsonObject;
        }else{
            int tempStatus = cuberReducer.getStatus();
            if(tempStatus == 2){
                jsonObject.put("result","1");
                return jsonObject;
            }
            cuberReducer.setStatus(Integer.parseInt(status));
            try{
                reducerService.buildReducerConfigFile();
                jsonObject.put("result", "0");
            }catch (Exception e){
                cuberReducer.setStatus(tempStatus);
                jsonObject.put("result","1");
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    @RequestMapping("/cuber/reducerList.shtml")
    public String reducerList(HttpServletRequest request, HttpServletResponse response,
                              ModelMap model) {
        HashMap<String,CuberReducer> cuberReducerMap = DataObject.getCuberReducerMap();
        List<CuberReducer> reducerList = new ArrayList<CuberReducer>();
        for(String s:cuberReducerMap.keySet()){
            CuberReducer reducer = cuberReducerMap.get(s);
            reducerList.add(reducer);
        }
        Collections.sort(reducerList, new Comparator<CuberReducer>() {
            public int compare(CuberReducer arg0, CuberReducer arg1) {
                int r0Status = arg0.getStatus();
                int r1Status = arg1.getStatus();
                if(r0Status > r1Status){
                    return 1;
                }if(r0Status == r1Status){
                    return 0;
                }else{
                    return -1;
                }
            }
        });

        model.addAttribute("reducerList", reducerList);
        return "/cuber/reducer_list";
    }

    @RequestMapping("/cuber/addReducer.shtml")
    public @ResponseBody
    JSONObject addReducer(HttpServletRequest request, HttpServletResponse response,
                          ModelMap model) {
        String data = request.getParameter("data");
        JSONObject jsonObject = JSON.parseObject(data);
        JSONObject resObject = new JSONObject();
        String reducerName = jsonObject.getString("reducerName");
        HashMap<String,CuberReducer> reducerMap = DataObject.getCuberReducerMap();
        if(reducerMap.containsKey(reducerName)){
            resObject.put("result","1");
            return resObject;
        }
        CuberReducer cuberReducer = new CuberReducer();
        cuberReducer.setReducerId(MatchUtil.generateMatch(2));
        cuberReducer.setReducerName(reducerName);
        cuberReducer.setSourceTable(jsonObject.getString("sourceTable"));
        cuberReducer.setStatPeriod(jsonObject.getString("statPeriod"));
        cuberReducer.setOutPutTable("CUBER_STAT_RESULT");
        String filterDateColumn = jsonObject.getString("filterDateColumn");
        if(!StringUtil.isMeanedEmpty(filterDateColumn)){
            cuberReducer.setFilterDateColumn(jsonObject.getString("filterDateColumn"));
        }
        String where = jsonObject.getString("where");
        if(!StringUtil.isEmpty(where)){
            cuberReducer.setWhere(where);
        }

        String dimension = jsonObject.getString("dimension");
        if(!StringUtil.isEmpty(dimension)){
            String[] columnArray = dimension.split(",");
            cuberReducer.setColumnArray(columnArray);
        }

        String statType = jsonObject.getString("statType");
        if(!StringUtil.isMeanedEmpty(statType)){
            cuberReducer.setStatType(statType);
        }else{
            resObject.put("result", "2");
            return resObject;
        }

        String statColumn = jsonObject.getString("statColumn");
        if(!StringUtil.isEmpty(statColumn)){
            cuberReducer.setStatColumn(statColumn);
        }
        String reducerDesc = jsonObject.getString("reducerDesc");
        if(!StringUtil.isEmpty(reducerDesc)){
            cuberReducer.setDesc(reducerDesc);
        }else{
            resObject.put("result","2");
            return resObject;
        }

        HashMap<String,CuberReducer> reducerHashMap = DataObject.getCuberReducerMap();
        reducerHashMap.put(cuberReducer.getReducerId(), cuberReducer);
        try{
            reducerService.buildReducerConfigFile();
        }catch (Exception e){
            e.printStackTrace();
        }

        resObject.put("result","0");
        return resObject;
    }

}
